package com.atguigu.gmall.search.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.pms.entity.BrandEntity;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import com.atguigu.gmall.search.pojo.Goods;
import com.atguigu.gmall.search.pojo.SearchRequestVo;
import com.atguigu.gmall.search.pojo.SearchResponseAttrVo;
import com.atguigu.gmall.search.pojo.SearchResponseVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public SearchResponseVo search(SearchRequestVo requestVo) {

        try {
            SearchResponse response = this.restHighLevelClient.search(new SearchRequest(new String[]{"goods"}, this.buildDsl(requestVo)), RequestOptions.DEFAULT);
            // 解析搜索结果集
            SearchResponseVo responseVo = this.parsedResult(response);
            // 设置分页参数
            responseVo.setPageNum(requestVo.getPageNum());
            responseVo.setPageSize(requestVo.getPageSize());
            return responseVo;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SearchResponseVo parsedResult(SearchResponse response){
        SearchResponseVo responseVo = new SearchResponseVo();

        // 解析查询结果集
        SearchHits hits = response.getHits();
        // 总记录数
        responseVo.setTotal(hits.getTotalHits());
        // 获取当前页的数据
        SearchHit[] hitsHits = hits.getHits();
        responseVo.setGoodsList(Stream.of(hitsHits).map(hitsHit -> {
            String json = hitsHit.getSourceAsString();
            Goods goods = JSON.parseObject(json, Goods.class);
            // 获取高亮结果字段
            Map<String, HighlightField> highlightFields = hitsHit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("title");
            goods.setTitle(highlightField.fragments()[0].string());
            return goods;
        }).collect(Collectors.toList()));

        // 解析聚合结果集
        Aggregations aggregations = response.getAggregations();

        // 解析品牌的聚合结果集
        ParsedLongTerms brandIdAgg = aggregations.get("brandIdAgg");
        List<? extends Terms.Bucket> brandBuckets = brandIdAgg.getBuckets();
        if (!CollectionUtils.isEmpty(brandBuckets)){
            // 把桶集合转化成品牌集合
            responseVo.setBrands(brandBuckets.stream().map(bucket -> {
                BrandEntity brandEntity = new BrandEntity();
                // 当前桶中的key就是品牌id
                brandEntity.setId(((Terms.Bucket) bucket).getKeyAsNumber().longValue());

                // 获取品牌名称子聚合
                Aggregations brandSubAgg = ((Terms.Bucket) bucket).getAggregations();
                ParsedStringTerms brandNameAgg = brandSubAgg.get("brandNameAgg");
                // 获取品牌名称子聚合中的桶
                List<? extends Terms.Bucket> nameBuckets = brandNameAgg.getBuckets();
                if (!CollectionUtils.isEmpty(nameBuckets)){
                    // 获取第一个桶中的key
                    brandEntity.setName(nameBuckets.get(0).getKeyAsString());
                }

                // 获取品牌logo的子聚合
                ParsedStringTerms logoAgg = brandSubAgg.get("logoAgg");
                List<? extends Terms.Bucket> logoAggBuckets = logoAgg.getBuckets();
                if (!CollectionUtils.isEmpty(logoAggBuckets)){
                    brandEntity.setLogo(logoAggBuckets.get(0).getKeyAsString());
                }
                return brandEntity;
            }).collect(Collectors.toList()));
        }

        // 解析分类的聚合结果集，获取分类列表
        ParsedLongTerms categoryIdAgg = aggregations.get("categoryIdAgg");
        List<? extends Terms.Bucket> categoryBuckets = categoryIdAgg.getBuckets();
        if (!CollectionUtils.isEmpty(categoryBuckets)){
            responseVo.setCategories(categoryBuckets.stream().map(bucket -> {
                CategoryEntity categoryEntity = new CategoryEntity();
                categoryEntity.setId(((Terms.Bucket) bucket).getKeyAsNumber().longValue());

                ParsedStringTerms categoryNameAgg = ((Terms.Bucket) bucket).getAggregations().get("categoryNameAgg");
                List<? extends Terms.Bucket> nameBuckets = categoryNameAgg.getBuckets();
                if (!CollectionUtils.isEmpty(nameBuckets)){
                    categoryEntity.setName(nameBuckets.get(0).getKeyAsString());
                }

                return categoryEntity;
            }).collect(Collectors.toList()));
        }

        // 解析规格参数的聚合结果集，获取规格参数列表
        // 嵌套聚合
        ParsedNested attrAgg = aggregations.get("attrAgg");
        // 获取嵌套聚合中子聚合
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        List<? extends Terms.Bucket> buckets = attrIdAgg.getBuckets();
        if (!CollectionUtils.isEmpty(buckets)){
            List<SearchResponseAttrVo> responseAttrVos = buckets.stream().map(bucket -> {
                SearchResponseAttrVo searchResponseAttrVo = new SearchResponseAttrVo();

                // 获取规格参数id
                searchResponseAttrVo.setAttrId(((Terms.Bucket) bucket).getKeyAsNumber().longValue());

                // 获取规格参数id的子聚合
                Aggregations attrSubAggs = ((Terms.Bucket) bucket).getAggregations();

                // 获取规格参数名称
                ParsedStringTerms attrNameAgg = attrSubAggs.get("attrNameAgg");
                List<? extends Terms.Bucket> nameBuckets = attrNameAgg.getBuckets();
                if (!CollectionUtils.isEmpty(nameBuckets)){
                    searchResponseAttrVo.setAttrName(nameBuckets.get(0).getKeyAsString());
                }

                // 获取规格参数值
                ParsedStringTerms attrValueAgg = attrSubAggs.get("attrValueAgg");
                List<? extends Terms.Bucket> valueAggBuckets = attrValueAgg.getBuckets();
                if (!CollectionUtils.isEmpty(valueAggBuckets)){
                    searchResponseAttrVo.setAttrValues(valueAggBuckets.stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList()));
                }

                return searchResponseAttrVo;
            }).collect(Collectors.toList());
            responseVo.setFilters(responseAttrVos);
        }

        return responseVo;
    }

    /**
     * 构建DSL条件
     * @param requestVo
     * @return
     */
    private SearchSourceBuilder buildDsl(SearchRequestVo requestVo) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        String keyword = requestVo.getKeyword();
        if (StringUtils.isBlank(keyword)){
            // TODO: 打广告
            throw new RuntimeException("搜索条件不能为空！");
        }

        // 1.构建查询和过滤条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        sourceBuilder.query(boolQueryBuilder);

        // 1.1. 构建匹配查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", keyword).operator(Operator.AND));

        // 1.2. 构建过滤条件
        // 1.2.1. 构建品牌过滤
        List<Long> brandId = requestVo.getBrandId();
        if (!CollectionUtils.isEmpty(brandId)){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", brandId));
        }

        // 1.2.2. 构建分类过滤
        List<Long> categoryId = requestVo.getCategoryId();
        if (!CollectionUtils.isEmpty(categoryId)){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("categoryId", categoryId));
        }

        // 1.2.3. 构建价格区间过滤
        Double priceFrom = requestVo.getPriceFrom();
        Double priceTo = requestVo.getPriceTo();
        if (priceFrom != null || priceTo != null){
            // 构建范围查询
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
            // 把范围查询放入过滤条件中
            boolQueryBuilder.filter(rangeQuery);
            // 如果priceFrom不为空，需要添加gte
            if (priceFrom != null) {
                rangeQuery.gte(priceFrom);
            }
            // 如果priceTo不为空，需要添加lte
            if (priceTo != null) {
                rangeQuery.lte(priceTo);
            }
        }

        // 1.2.4. 构建是否有货
        Boolean store = requestVo.getStore();
        if (store != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("store", store));
        }

        // 1.2.5. 构建规格参数过滤 ["4:8G-12G", "5:128G-256G"]
        List<String> props = requestVo.getProps();
        if (!CollectionUtils.isEmpty(props)){
            for (String prop : props) { // 4:8G-12G
                // 如果当前prop不包含:说明不合法的字符串，忽略该过滤条件
                if (StringUtils.indexOf(prop, ":") <= 0){
                    continue;
                }
                Long attrId = Long.valueOf(StringUtils.substringBefore(prop, ":"));
                String[] attrValues = StringUtils.split(StringUtils.substringAfter(prop, ":"), "-");

                // 添加嵌套过滤
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                boolQueryBuilder.filter(QueryBuilders.nestedQuery("searchAttrs", boolQuery, ScoreMode.None));
                // 给bool查询添加条件
                boolQuery.must(QueryBuilders.termQuery("searchAttrs.attrId", attrId));
                boolQuery.must(QueryBuilders.termsQuery("searchAttrs.attrValue", attrValues));
            }
        }

        // 2.构建排序条件
        Integer sort = requestVo.getSort();
        if (sort != null) {
            switch (sort) {
                case 1: sourceBuilder.sort("price", SortOrder.DESC); break;
                case 2: sourceBuilder.sort("price", SortOrder.ASC); break;
                case 3: sourceBuilder.sort("sales", SortOrder.DESC); break;
                case 4: sourceBuilder.sort("createTime", SortOrder.DESC); break;
                default:
                    sourceBuilder.sort("_score", SortOrder.DESC);
                    break;
            }
        }

        // 3.构建分页
        Integer pageNum = requestVo.getPageNum();
        Integer pageSize = requestVo.getPageSize();
        sourceBuilder.from((pageNum - 1) * pageSize);
        sourceBuilder.size(pageSize);

        // 4.构建高亮
        sourceBuilder.highlighter(new HighlightBuilder()
                .field("title")
                .preTags("<font style='color:red;'>")
                .postTags("</font>"));

        // 5.构建聚合
        // 5.1. 构建品牌聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("brandIdAgg").field("brandId")
                .subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName"))
                .subAggregation(AggregationBuilders.terms("logoAgg").field("logo")));

        // 5.2. 构建分类聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("categoryIdAgg").field("categoryId")
                .subAggregation(AggregationBuilders.terms("categoryNameAgg").field("categoryName")));

        // 5.3. 构建规格参数聚合
        sourceBuilder.aggregation(AggregationBuilders.nested("attrAgg", "searchAttrs")
                .subAggregation(AggregationBuilders.terms("attrIdAgg").field("searchAttrs.attrId")
                        .subAggregation(AggregationBuilders.terms("attrNameAgg").field("searchAttrs.attrName"))
                        .subAggregation(AggregationBuilders.terms("attrValueAgg").field("searchAttrs.attrValue"))));

        // 6. 构建结果集过滤
        sourceBuilder.fetchSource(new String[]{"skuId", "title", "subtitle", "price", "defaultImage"}, null);
        System.out.println(sourceBuilder);
        return sourceBuilder;
    }
}
